/*
 *所有关于Consumer类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*ConsumerService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VOL.Core.BaseProvider;
using VOL.Core.Extensions.AutofacManager;
using VOL.Entity.DomainModels;
using System.Linq;
using VOL.Core.Utilities;
using System.Linq.Expressions;
using VOL.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Dongxing.IRepositories;
using Microsoft.Extensions.Caching.Memory;
using SkiaSharp;
using System.Net;
using VOL.Core.Configuration;
using VOL.Core.Enums;
using VOL.Core.ManageUser;
using VOL.Entity.DomainModels.Dto;
using Dm.filter.log;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;

namespace VOL.Dongxing.Services
{
    public partial class ConsumerService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IConsumerRepository _repository;//访问数据库

        [ActivatorUtilitiesConstructor]
        public ConsumerService(
            IConsumerRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }


        WebResponseContent webResponse = new WebResponseContent();

        /// <summary>
        /// WebApi登陆
        /// </summary>
        /// <param name="loginInfo"></param>
       
        /// <returns></returns>
        public async Task<WebResponseContent> Login(LoginConsumerInfo loginInfo)//, bool verificationCode = true
        {
            string msg = string.Empty;
            //   2020.06.12增加验证码
            //IMemoryCache memoryCache = _httpContextAccessor.HttpContext.GetService<IMemoryCache>();
            
            //string cacheCode = (memoryCache.Get(loginInfo.UUID) ?? "").ToString();
            //if (string.IsNullOrEmpty(cacheCode))
            //{
            //    return webResponse.Error("验证码已失效");
            //}
            //if (cacheCode.ToLower() != loginInfo.VerificationCode.ToLower())
            //{
            //    memoryCache.Remove(loginInfo.UUID);
            //    return webResponse.Error("验证码不正确");
            //}
            try
            {
                Consumer user = await _repository.FindAsIQueryable(x => x.UserName == loginInfo.UserName).FirstOrDefaultAsync();

                if (user == null || loginInfo.Password.Trim().EncryptDES(AppSetting.Secret.User) != (user.Password ?? ""))
                    return webResponse.Error(ResponseType.LoginError);

                string token = JwtHelper.IssueJwt(new UserInfo()
                {
                    User_Id = user.Id,
                    UserName = user.UserName,
                    //Role_Id = user.Role_Id
                });
                user.Token = token;
                webResponse.Data = new { token, userName = user.UserName, nickName = user.NickName,id=user.Id};
                _repository.Update(user, x => x.Token, true);
                //UserContext.Current.LogOut(user.Id); //应该要去掉...
                //int UserId = UserContext.Current.UserId;

                loginInfo.Password = string.Empty;

                return webResponse.OK(ResponseType.LoginSuccess);
            }
            catch (Exception ex)
            {
                //msg = ex.Message + ex.StackTrace;
                //if (_httpContextAccessor.HttpContext.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                //{
                //    throw new Exception(ex.Message + ex.StackTrace);
                //}
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {
                //memoryCache.Remove(loginInfo.UUID);
                //Logger.Info(LoggerType.Login, loginInfo.Serialize(), webResponse.Message, msg);//日志
            }
        }



        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="saveDataModel"></param>
        /// <returns></returns>
        public override WebResponseContent Add(SaveModel saveDataModel)
        {
            //此处saveModel是从前台提交的原生数据，可对数据进修改过滤
            AddOnExecute = (SaveModel saveModel) =>
            {
                //如果返回false,后面代码不会再执行
                return webResponse.OK();
            };

            // 在保存数据库前的操作，所有数据都验证通过了，这一步执行完就执行数据库保存
            AddOnExecuting =  (Consumer consumer, object list) =>
            {
                Consumer user = _repository.FindAsIQueryable(x => x.UserName == consumer.UserName).FirstOrDefault();
                if (user != null )
                {//中断执行
                    return webResponse.Error("有重复用户名");
                }

                consumer.CreateTime = DateTime.Now;
                consumer.Password = consumer.Password.Trim().EncryptDES(AppSetting.Secret.User);

                return webResponse.OK();
            };

            return base.Add(saveDataModel);
        }


        /// <summary>
        /// 编辑操作
        /// </summary>
        /// <param name="saveModel"></param>
        /// <returns></returns>
        public override WebResponseContent Update(SaveModel saveModel)
        {
            //注意：如果要给其他字段设置值，请在此处设置,如：（代码生成器上将字段编辑行设置为0，然后点生成model）
            //saveModel.MainData["字段"] = "值";

            //此处saveModel是从前台提交的原生数据，可对数据进修改过滤
            UpdateOnExecute = (SaveModel model) =>
            {
                ////这里的设置配合下面order.Remark = "888"代码位置使用
                // saveModel.MainData.TryAdd("Remark", "1231");

                //如果不想前端提交某些可以编辑的字段的值,直接移除字段
                // saveModel.MainData.Remove("字段");

                //如果返回false,后面代码不会再执行
                return webResponse.OK();

            };

            //编辑方法保存数据库前处理
            UpdateOnExecuting = (Consumer consumer, object addList, object updateList, List<object> delKeys) =>
            {
                Consumer user = _repository.FindAsIQueryable(x => x.UserName == consumer.UserName).FirstOrDefault();
                if (user != null)
                {//中断执行
                    return webResponse.Error("有重复用户名");
                }


                consumer.Password = consumer.Password.Trim().EncryptDES(AppSetting.Secret.User);

                ////新增的明细表
                //List<SellOrderList> add = addList as List<SellOrderList>;
                ////修改的明细表
                //List<SellOrderList> update = updateList as List<SellOrderList>;
                ////删除明细表Id
                //var guids = delKeys?.Select(x => (Guid)x);

                //设置webResponse.Code = "-1"会中止后面代码执行，与返回 webResponse.Error()一样，区别在于前端提示的是成功或失败
                //webResponse.Code = "-1";
                // webResponse.Message = "测试强制返回";
                //return webResponse.OK("ok");

                return webResponse.OK();
            };

           

            return base.Update(saveModel);
        }


    }
}
